<template>
  <n-card :bordered="false" class="mt-3">
    <BasicTable
      :columns="reportColumns"
      :request="loadDataTable"
      :row-key="(row:ReportData) => row.reportID"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
      :striped="true"
    >
      <template #tableTitle>
        <n-space>
          <n-button type="primary" @click="handleRefresh">
            <template #icon>
              <n-icon>
                <ReloadOutlined />
              </n-icon>
            </template>
            刷新
          </n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { reportColumns, ReportData } from './columns';
import { ReloadOutlined } from '@vicons/antd';
import { useMessage } from 'naive-ui';
import { ReportRecordApi } from '@/api/ReportRecordApi';
import { useRouter } from 'vue-router';

const actionRef = ref();
const message = useMessage();
const router = useRouter();

// 操作列
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '查看',
          onClick: handleView.bind(null, record),
        },
        {
          label: '处理',
          onClick: handleProcess.bind(null, record),
          disabled: record.reportStatus === 'handled',
          auth: ['admin'],
        },
      ],
    });
  },
});

// 加载表格数据
const loadDataTable = async (res) => {
  try {
    // 获取所有举报记录
    const response = await ReportRecordApi.getAllReportRecords();

    return {
      list: response,
      page: res.page,
      pageSize: res.pageSize,
      pageCount: Math.ceil(response.length / res.pageSize),
      itemCount: response.length,
    };
  } catch (error) {
    console.error('获取举报记录列表失败:', error);
    message.error('获取举报记录列表失败: ' + (error?.message || '未知错误'));
    return {
      list: [],
      page: 1,
      pageSize: 10,
      pageCount: 0,
      itemCount: 0,
    };
  }
};

// 选中行事件
function onCheckedRow(rowKeys) {
  console.log('选中的行:', rowKeys);
}

// 刷新表格
function handleRefresh() {
  actionRef.value.reload();
  message.success('刷新成功');
}

// 查看举报详情
function handleView(record: ReportData) {
  router.push({
    name: 'report_detail',
    params: {
      id: record.reportID
    }
  });
}

// 处理举报
async function handleProcess(record: ReportData) {
  try {
    // 更新举报状态为已处理
    await ReportRecordApi.updateReportRecord(record.reportID, {
      ...record,
      reportStatus: 'handled',
      handlingTime: new Date().toISOString(),
      handlingResult: '管理员已处理'
    });
    message.success('举报已处理');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}
</script>

<style lang="less" scoped></style>
